package com.trace.app.commend;

import com.trace.app.contract.RecordContractUtil;
import com.trace.app.entity.Record;
import com.trace.app.service.RecordService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.ContractException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

@Slf4j
@AllArgsConstructor
//@Component
public class TraceCommandLineRunner implements CommandLineRunner {
    @Resource
    private RecordService recordService;

    @Resource
    private RecordContractUtil recordContractUtil;

    @Override
    public void run(String... args) throws Exception {
        List<Record> recordList = recordService.list();
        recordList.stream().forEach(record -> {
            try {
                Record recordByKey = recordContractUtil.getRecordByKey(String.valueOf(record.getId()));

                if (!Objects.isNull(recordByKey)) {
                    recordContractUtil.deleteRecordByKey(String.valueOf(recordByKey.getId()));
                }
                recordContractUtil.createRecord(record);

            } catch (ContractException | InterruptedException | TimeoutException e) {
                throw new RuntimeException(e);
            }

        });

    }
}